package com.example.controller;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.ResponseResult;
import com.example.entity.Blog;
import com.example.mapper.BlogMapper;
import com.example.service.BlogService;
import com.example.util.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Qiu
 * @since 2020-06-30
 */
@RestController
public class BlogController {

    @Autowired
    private BlogService blogService;

    @GetMapping("blogs")
    public ResponseResult list(@RequestParam(defaultValue = "1") Integer currentPage){
        Page<Blog> page = new Page<>(currentPage, 5);
        IPage<Blog> blogIPage = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
        return ResponseResult.success(blogIPage);
    }
    @GetMapping("blog/{id}")
    public ResponseResult detail(@PathVariable Integer id){
        Blog blog = blogService.getById(id);
        Assert.notNull(blog,"该博客已被删除");

        return ResponseResult.success(blog);
    }
    @RequiresAuthentication
    @PutMapping("blog/edit")
    public ResponseResult list(@RequestBody Blog blog){

        if (blog.getId()!=null){
            blog.setUserId(ShiroUtils.getProfile().getId().longValue());
            Assert.isTrue(blog.getUserId().longValue() == ShiroUtils.getProfile().getId().longValue(),"没有编辑权限");

            blogService.saveOrUpdate(blog);
        }else{
            blog.setUserId(ShiroUtils.getProfile().getId().longValue());
            blogService.save(blog);
        }
        return ResponseResult.success(null);
    }
}
